package com.blog.servlet;

import com.blog.dao.CategoryDao;
import com.blog.dao.impl.CategoryDaoImpl;
import com.blog.entity.Category;
import com.blog.entity.User;
import com.blog.util.StringUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 分类管理Servlet
 */
@WebServlet("/category")
public class CategoryServlet extends HttpServlet {
    private CategoryDao categoryDao = new CategoryDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if (action == null) action = "list";

        switch (action) {
            case "add":
                // 跳转到添加分类页面
                request.getRequestDispatcher("/category/add.jsp").forward(request, response);
                break;
            case "edit":
                // 跳转到编辑分类页面
                editCategory(request, response);
                break;
            case "delete":
                // 删除分类
                deleteCategory(request, response);
                break;
            default:
                // 显示分类列表
                listCategory(request, response);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if (action == null) {
            response.sendRedirect(request.getContextPath() + "/category");
            return;
        }

        switch (action) {
            case "add":
                addCategory(request, response);
                break;
            case "edit":
                updateCategory(request, response);
                break;
            default:
                response.sendRedirect(request.getContextPath() + "/category");
                break;
        }
    }

    // 显示分类列表
    private void listCategory(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        List<Category> categoryList = categoryDao.findByUserId(loginUser.getId());
        request.setAttribute("categoryList", categoryList);

        request.getRequestDispatcher("/category/list.jsp").forward(request, response);
    }

    // 添加分类
    private void addCategory(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String name = request.getParameter("name");
        String description = request.getParameter("description");

        if (StringUtil.isEmpty(name)) {
            request.setAttribute("errorMsg", "分类名称不能为空！");
            request.getRequestDispatcher("/category/add.jsp").forward(request, response);
            return;
        }

        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        Category category = new Category(name, description, loginUser.getId());
        int rows = categoryDao.add(category);

        if (rows > 0) {
            // 添加成功，重定向到分类列表
            response.sendRedirect(request.getContextPath() + "/category");
        } else {
            request.setAttribute("errorMsg", "添加分类失败，请重试！");
            request.getRequestDispatcher("/category/add.jsp").forward(request, response);
        }
    }

    // 跳转到编辑分类页面
    private void editCategory(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (StringUtil.isEmpty(idStr)) {
            request.setAttribute("errorMsg", "分类ID不能为空！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            request.setAttribute("errorMsg", "分类ID格式错误！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        Category category = categoryDao.findById(id);
        if (category == null) {
            request.setAttribute("errorMsg", "分类不存在！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        // 验证权限
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser.getId() != category.getUserId()) {
            request.setAttribute("errorMsg", "没有权限编辑该分类！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        request.setAttribute("category", category);
        request.getRequestDispatcher("/category/edit.jsp").forward(request, response);
    }

    // 更新分类
    private void updateCategory(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String idStr = request.getParameter("id");
        String name = request.getParameter("name");
        String description = request.getParameter("description");

        if (StringUtil.isEmpty(idStr) || StringUtil.isEmpty(name)) {
            request.setAttribute("errorMsg", "分类ID和名称不能为空！");
            request.getRequestDispatcher("/category/edit.jsp").forward(request, response);
            return;
        }

        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            request.setAttribute("errorMsg", "分类ID格式错误！");
            request.getRequestDispatcher("/category/edit.jsp").forward(request, response);
            return;
        }

        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        Category category = new Category(name, description, loginUser.getId());
        category.setId(id);

        int rows = categoryDao.update(category);
        if (rows > 0) {
            response.sendRedirect(request.getContextPath() + "/category");
        } else {
            request.setAttribute("errorMsg", "更新分类失败，请重试！");
            request.setAttribute("category", category);
            request.getRequestDispatcher("/category/edit.jsp").forward(request, response);
        }
    }

    // 删除分类
    private void deleteCategory(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (StringUtil.isEmpty(idStr)) {
            request.setAttribute("errorMsg", "分类ID不能为空！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            request.setAttribute("errorMsg", "分类ID格式错误！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        // 验证权限
        Category category = categoryDao.findById(id);
        if (category == null) {
            request.setAttribute("errorMsg", "分类不存在！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser.getId() != category.getUserId()) {
            request.setAttribute("errorMsg", "没有权限删除该分类！");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        int rows = categoryDao.delete(id);
        response.sendRedirect(request.getContextPath() + "/category");
    }
}